/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。
 * 版权所有：忠旺机械设备制造有限公司
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。
 * 软件版本：Ver 1.0.0
 * 文件路径：com.zhongwang.mms.module.purchase.excelListener
 * 创建时间：2020年04月28日 12时56分
 **/
package com.zhongwang.mms.module.purchase.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.zhongwang.mms.base.BaseService;
import com.zhongwang.mms.common.ImportCallBack;
import com.zhongwang.mms.gen.entity.PChangeOrder;
import com.zhongwang.mms.gen.entity.PInventory;
import com.zhongwang.mms.gen.entity.TProject;
import com.zhongwang.mms.module.basic.dao.BoardDao;
import com.zhongwang.mms.module.basic.dao.TProjectDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.basic.model.TProjectModel;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.purchase.dao.PurChangeDao;
import com.zhongwang.mms.module.purchase.dao.PurCheckDao;
import com.zhongwang.mms.module.purchase.dao.PurPInventoryDao;
import com.zhongwang.mms.module.purchase.model.*;
import com.zhongwang.mms.module.purchase.model.check.PCheckDetailExcelModel;
import com.zhongwang.mms.module.purchase.service.PurChangeService;
import com.zhongwang.mms.module.purchase.service.PurlnvQueryService;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.BigDecimalUtils;
import com.zhongwang.mms.util.ShiroUtils;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.zhongwang.mms.config.timingtask.StatisticalTimingTask.getVWProjectByCode;

/**
 * @ClassName： PChangeOrderListener
 * @Description： 批量串料标记导入 Listenter
 * @Author： 徐一贺
 * @Date： 2020年6月15日14:44:50
 * @Version： V1.0
 **/
public class PChangeOrderListener extends AnalysisEventListener<PChangeOrderExcelModel> {
    private PurChangeDao purChangeDao;
    private BoardDao boardDao;
    private LogService logService;
    private ImportCallBack callBack;
    private BaseService baseService;
    private PurPInventoryDao purPInventoryDao;
    private List<PChangeImportExportLogModel> errorInfoList = new ArrayList<>();
    private TWarehouseInfoDao tWarehouseInfoDao;
    private TProjectDao tProjectDao;
    private Date appDate;
    private BoardService boardService;

    private List<TProjectModel> TProjectModels;

    public PChangeOrderListener(PurChangeDao purChangeDao,
                                BoardDao boardDao,
                                ImportCallBack callBack,
                                LogService logService,
                                BaseService baseService,
                                PurPInventoryDao purPInventoryDao,
                                TWarehouseInfoDao tWarehouseInfoDao,
                                TProjectDao tProjectDao,
                                BoardService boardService,
                                List<TProjectModel> TProjectModels
    ) {
        this.purChangeDao = purChangeDao;
        this.boardDao = boardDao;
        this.callBack = callBack;
        this.logService = logService;
        this.baseService = baseService;
        this.purPInventoryDao = purPInventoryDao;
        this.tWarehouseInfoDao = tWarehouseInfoDao;
        this.tProjectDao = tProjectDao;
        this.boardService = boardService;
        this.TProjectModels = TProjectModels;
        appDate = new Date();
    }

    private TProjectModel getProject(String code){
        for (int i = 0; i < TProjectModels.size(); i++) {
            if (TProjectModels.get(i).getCode().toUpperCase().equals(code.toUpperCase())){
                return  TProjectModels.get(i);
            }
        }
        return null;
    }

    @Override
    public void invoke(PChangeOrderExcelModel data, AnalysisContext analysisContext) {
        String errorInfo = "";
        //开始进行常规验证
        if (null == data.getCeoUseItyId() || data.getCeoUseItyId().equals("")) {
            errorInfo += "【库存ID（禁改）】列不可为空也不可为0，请您修改！" + "\r\n";
        } else {
            try {
                Integer ceoNeedItyId = Integer.valueOf(data.getCeoUseItyId());
                if (purChangeDao.getInventoryPrimaryKey(ceoNeedItyId) == null) {
                    errorInfo += "【库存ID（禁改）】列ID不可修改！" + "\r\n";
                }
            } catch (Exception e) {
                errorInfo += "【库存ID（禁改）】列ID不可修改！" + "\r\n";
            }
        }
        if (null == data.getCeoNeedProCode() || data.getCeoNeedProCode().equals("")) {
            errorInfo += "【提报计划项目编号】列不可为空也不可不填，请您修改！" + "\r\n";
        } else if (getVWProjectByCode(data.getCeoNeedProCode()) == null) {
            errorInfo += "【提报计划项目编号】列项目编号不存在，请您修改！" + "\r\n";
        } else if (data.getCeoNeedProCode().toUpperCase().trim().equals(data.getCeoUseProCode().toUpperCase().trim())) {
            errorInfo += "【在库项目编号】与【提报计划项目编号】不可相同，请您修改！" + "\r\n";
        }
        if (null == data.getCeoNeedProName() || data.getCeoNeedProName().equals("")) {
            errorInfo += "【提报计划项目名称】列不可为空也不可不填，请您修改！" + "\r\n";
        }
        if (null == data.getCeoUseProCode() || data.getCeoUseProCode().equals("")) {
            errorInfo += "【在库项目编号】列不可为空也不可不填，请您修改！" + "\r\n";
        } else if (getVWProjectByCode(data.getCeoUseProCode()) == null) {
            errorInfo += "【在库项目编号】列项目编号不存在，请您修改！" + "\r\n";
        }
        if (null == data.getCeoNeedMatName() || data.getCeoNeedMatName().equals("")) {
            errorInfo += "【提报计划物料描述】列不可为空也不可不填，请您修改！" + "\r\n";
        } else if (data.getCeoNeedMatName().length() > 1000) {
            errorInfo += "【提报计划物料描述】列项内容过多，请保持所有字符在1000个以内，包括回车，请您修改！" + "\r\n";
        }
        if (null == data.getCeoNeedNum() || data.getCeoNeedNum().equals("")) {
            errorInfo += "【提报计划数量】列不可为空也不可不填，请您修改！" + "\r\n";
        } else {
            try {
                Double ceoNeedNum = Double.valueOf(data.getCeoNeedNum());
                if (ceoNeedNum <= 0) {
                    errorInfo += "【提报计划数量】列的数字必须大于0，请您修改！" + "\r\n";
                }
            } catch (Exception e) {
                errorInfo += "【提报计划数量】列只能是数字，请修改！" + "\r\n";
            }

        }
        if (null != data.getCeoRemark() && !data.getCeoRemark().equals("") && data.getCeoRemark().length() > 255) {
            errorInfo += "【提报计划标准号】列项内容过多，请保持所有字符在255个以内，包括回车，请您修改！" + "\r\n";
        }

        if (null != data.getCeoRemark() && !data.getCeoRemark().equals("")) {
            if (data.getCeoRemark().length() > 255) {
                errorInfo += "【备注】列项内容过多，请保持所有字符在255个以内，包括回车，请您修改！" + "\r\n";
            }
        }
        if (data.getCeoUseItyId() != null && !data.getCeoUseItyId().equals("")) {
            PInventoryModel pInventoryModel = null;
            try {
                pInventoryModel = purPInventoryDao.getInventoryModelByPrimaryKey(data.getCeoUseItyId());
            } catch (Exception e) {
                errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
            }
            if (pInventoryModel == null) {
                errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
            } else {
                if (pInventoryModel.getItyAvaNum() <= 0 || pInventoryModel.getItyNum() <= 0) {
                    errorInfo += "所选库存可用数量不足，请您修改！" + "\r\n";
                } else {
                    try {
                        if (BigDecimalUtils.div(pInventoryModel.getItyAvaNum(), Double.valueOf(data.getCeoNeedNum()), 3) < 1) {
                            errorInfo += "所选库存可用数量不足，请您修改！" + "\r\n";
                        }
                    } catch (Exception e) {
                        errorInfo += "【提报计划数量】列只能是数字，请修改！" + "\r\n";
                    }
                }
            }
        }
        PInventory pInventory = null;
        if (null != data.getCeoUseItyId() && !data.getCeoUseItyId().equals("")) {
            try {
                pInventory = purChangeDao.getInventoryPrimaryKey(Integer.valueOf(data.getCeoUseItyId()));
            } catch (NumberFormatException e) {
                errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
            }
            if (pInventory == null) {
                errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
            } else if (pInventory.getItyStockType().equals(1)) {
                errorInfo += "该物料在库类型为库存在库，无法串料，请修改！" + "\r\n";
            }
        }
        if (!errorInfo.equals("") && pInventory != null) {
            //根据主键获取库存信息
            PChangeImportExportLogModel model = new PChangeImportExportLogModel();
            model.setCeoUseItyId(pInventory.getItyId().toString());
            model.setCeoUseProCode(pInventory.getItyProCode());
            model.setCeoUseProName(pInventory.getItyProName());
            model.setCeoUseMatName(pInventory.getItyMatDesc());
            model.setCeoUseNum(pInventory.getItyAvaNum().toString());
            model.setCeoUseWhiName(tWarehouseInfoDao.selectByPrimaryKey(pInventory.getItyWhiId()).getWhiName());
            model.setCeoUsePosition(pInventory.getItyPosition());
            model.setCeoUseItyStockType((pInventory.getItyStockType() == 1 ? "库存在库" : "项目在库"));
            model.setCeoTrackCode(pInventory.getItyTrackCode());
            model.setCeoSapCode(data.getCeoSapCode());
            String ceoUseStatus = "";
            TProjectModel tProjectModel = getProject(pInventory.getItyProCode());
            if (tProjectModel != null) {
                switch (tProjectModel.getProProductionStatus()) {
                    case 1:
                        ceoUseStatus = "制作中";
                        break;
                    case 2:
                        ceoUseStatus = "待制作";
                        break;
                    case 3:
                        ceoUseStatus = "暂缓";
                        break;
                    case 4:
                        ceoUseStatus = "完成";
                        break;
                    default:
                        ceoUseStatus = "无状态";
                        break;
                }
            } else {
                ceoUseStatus = "无状态";
            }

            model.setCeoUseStatus(ceoUseStatus);
            String ceoNeedProCode = boardService.projectCodeHandle(data.getCeoNeedProCode());
            model.setCeoNeedProCode(ceoNeedProCode);
            model.setCeoNeedProName(data.getCeoNeedProName());
            model.setCeoNeedMatName(data.getCeoNeedMatName());
            model.setCeoNeedStandardNo(data.getCeoNeedStandardNo());
            model.setCeoNeedNum(data.getCeoNeedNum());
            model.setCeoRemark(data.getCeoRemark());
            model.setCeoAppPersonId(ShiroUtils.getUserId());
            model.setCeoAppDate(appDate);
            //导入导出类别
            model.setCeoType(1);
            model.setCeoWarnInfo(errorInfo);
            model.setCeoStatus(1);
            errorInfoList.add(model);
        } else if (!errorInfo.equals("") && pInventory == null) {
            //根据主键获取库存信息
            PChangeImportExportLogModel model = new PChangeImportExportLogModel();
            model.setCeoUseProCode(null);
            model.setCeoUseProName(null);
            model.setCeoUseMatName(null);
            model.setCeoUseNum(null);
            model.setCeoUseWhiName(null);
            model.setCeoUsePosition(null);
            model.setCeoUseItyStockType(null);
            model.setCeoTrackCode(null);
            model.setCeoSapCode(null);
            String ceoUseStatus = "";
            if (data.getCeoUseProCode() != null && !data.getCeoUseProCode().equals("")) {
                TProjectModel tProjectModel = getProject(data.getCeoUseProCode());
                if (tProjectModel != null) {
                    switch (tProjectModel.getProProductionStatus()) {
                        case 1:
                            ceoUseStatus = "制作中";
                            break;
                        case 2:
                            ceoUseStatus = "待制作";
                            break;
                        case 3:
                            ceoUseStatus = "暂缓";
                            break;
                        case 4:
                            ceoUseStatus = "完成";
                            break;
                        default:
                            ceoUseStatus = "无状态";
                            break;
                    }
                } else {
                    ceoUseStatus = "无状态";
                }
                model.setCeoUseStatus(ceoUseStatus);
            } else {
                model.setCeoUseStatus(null);
            }
            if (data.getCeoNeedProCode() != null) {
                String ceoNeedProCode = boardService.projectCodeHandle(data.getCeoNeedProCode());
                model.setCeoNeedProCode(ceoNeedProCode);
            } else {
                model.setCeoNeedProCode(null);
            }
            model.setCeoNeedProName(data.getCeoNeedProName());
            model.setCeoNeedMatName(data.getCeoNeedMatName());
            model.setCeoNeedStandardNo(data.getCeoNeedStandardNo());
            model.setCeoNeedNum(data.getCeoNeedNum());
            model.setCeoRemark(data.getCeoRemark());
            model.setCeoAppPersonId(ShiroUtils.getUserId());
            model.setCeoAppDate(appDate);
            //导入导出类别
            model.setCeoType(1);
            model.setCeoWarnInfo(errorInfo);
            model.setCeoStatus(1);
            errorInfoList.add(model);
        } else {
            try {
                //根据主键获取库存信息
                PInventory ceoUsePInventory = purChangeDao.getInventoryPrimaryKey(Integer.valueOf(data.getCeoUseItyId()));
                PChangeOrder param = new PChangeOrder();
                param.setCeoUseItyId(ceoUsePInventory.getItyId());
                param.setCeoUseProCode(ceoUsePInventory.getItyProCode());
                param.setCeoUseMatName(ceoUsePInventory.getItyMatDesc());
                param.setCeoUseNum(new BigDecimal(ceoUsePInventory.getItyAvaNum()).doubleValue());
                param.setCeoUseWhiId(ceoUsePInventory.getItyWhiId());
                param.setCeoUsePosition(ceoUsePInventory.getItyPosition());
                param.setCeoUseProName(ceoUsePInventory.getItyProName());
                String ceoNeedProCode = boardService.projectCodeHandle(data.getCeoNeedProCode());
                param.setCeoNeedProCode(ceoNeedProCode);
                param.setCeoNeedProName(data.getCeoNeedProName());
                param.setCeoNeedMatName(data.getCeoNeedMatName());
                param.setCeoNeedNum(new BigDecimal(data.getCeoNeedNum()).doubleValue());
                param.setCeoUseStatus(data.getCeoUseStatus());
                param.setCeoRemark(data.getCeoRemark());
                param.setCeoItyType("p");
                param.setCeoAppPersonId(ShiroUtils.getUser().getId());
                param.setCeoUseMatCode(ceoUsePInventory.getItySapCode());
                param.setCeoNeedStandardNo(data.getCeoNeedStandardNo());
                param.setCeoAppDate(appDate);
                param.setCeoAppyStatus(1);
                if (ceoUsePInventory.getItyAvaNum() > param.getCeoNeedNum()) {
                    param.setCeoType(2);
                } else {
                    param.setCeoType(1);
                }
                if (param.getCeoId() == null || param.getCeoId() == 0) {
                    //更改库存可用数量
                    ceoUsePInventory.setItyAvaNum(ceoUsePInventory.getItyAvaNum() - param.getCeoNeedNum());
                    purPInventoryDao.updateItyAvaNumByPrimary(ceoUsePInventory);
                    param.setCeoCode(generateCCOrderCode());
                    purChangeDao.insertSelective(param);
                } else if (param.getCeoId() != 0) {
                    //获取原串料数据
                    PChangeOrderModel source = purChangeDao.getPChangeOrderByPrimaryKey(param.getCeoId());
                    ceoUsePInventory.setItyAvaNum(source.getCeoNeedNum() + ceoUsePInventory.getItyAvaNum() - param.getCeoNeedNum());
                    purPInventoryDao.updateItyAvaNumByPrimary(ceoUsePInventory);
                    purChangeDao.uppdateSelective(param);
                }
                logService.saveLog("【外购件】保存串料标记", "保存的标记的库存物料描述：" + ceoUsePInventory.getItyMatDesc());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (errorInfoList.size() > 0) {
            callBack.onWarning(errorInfoList);
        } else {
            callBack.onSuccess();
        }
    }


    @Override
    public void onException(Exception exception, AnalysisContext context) {

    }

    /**
     * @FunctionName: generateCCOrderCode
     * @Description: 获取串料单编码
     * @Author: 徐一贺
     * @CreateDate: 2020/4/16 13:06
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Version:
     */
    private String generateCCOrderCode() {
        String newGeneratePRKOrderCode = "";
        //获取最后编码
        String lastCCOrderCode = purChangeDao.findLastCCOrderCode();
        if (null == lastCCOrderCode) {
            lastCCOrderCode = "";
        }
        //获取当前时间简码
        String datetimeCode = new SimpleDateFormat("yyMMdd").format(new Date());
        Integer sn = 0;
        if (lastCCOrderCode.length() > 0) {
            //获取外购件库最新最后的入库单号
            sn = Integer.parseInt(lastCCOrderCode.substring(9));
        }

        if (lastCCOrderCode.length() == 0) {
            newGeneratePRKOrderCode = "CC" + new SimpleDateFormat("yyMMdd").format(new Date()) + "000001";
        } else if (!lastCCOrderCode.substring(2, 8).equals(datetimeCode)) {
            newGeneratePRKOrderCode = "CC" + new SimpleDateFormat("yyMMdd").format(new Date()) + "000001";
        } else {
            newGeneratePRKOrderCode = "CC" + new SimpleDateFormat("yyMMdd").format(new Date()) + String.format("%06d", (sn + 1));
        }
        return newGeneratePRKOrderCode;
    }
}